<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>小萌神订餐网</title>
<!-- 图标 -->
<link rel="short icon" href="image/eat0.ico" />
<link rel="stylesheet" href="css/index.css" />
</head>
<body>
 
  <div id="app">
 
	<div class="head">
		小萌神订餐网
		<div class="right">
			<span class="showlogin" id="showlogin" @click="loginflag=!loginflag" v-if="!isLogin">登录</span>
			<span id="exitspan" v-if="isLogin" >
<!--				style="display:none"-->
				欢迎您:{{username}} | <a href="" @click.prevent="logout()"> 退出</a>
			</span>
		</div>
	</div>
	<div class="content">
		<ul class="allfoods" id="allfoods">
			<li v-for="(item,index) in data">
				<h3 @click="showFood(item.fid)">{{item.fname}}</h3>
				<div class="fooddesc" style="display:none" v-show="item.status">
					<img :src="'image/' + item.fphoto" class="foodimg" />
					<article class="foodprice">
						<p>菜品描述：{{item.detail}}</p>
						<p class="normalprice">原价：￥{{item.normprice}}</p>
						<p class="realprice">特价：￥{{item.realprice}}</p>
						<p class="buybtn" @click="addCart(item.fid,1)">加入购物车</p>
<!--						<p>赞{{item.praise}}-->
<!--							<span v-if="isLogin" @click="clickPraise(item.fid,index)">-->
<!--								来一发-->
<!--							</span></p>-->
					</article>
				</div>
			</li>
			
		</ul>
		<!-- 分页模块 -->
		<div style="background-color: white;color: red">
			<a @click.prevent="clickPage(1)">第一页</a>
			<a @click.prevent="clickPage(pagebean.pre)" :page-data="pagebean.pre">上一页 {{pagebean.pre}}</a>
			<a @click.prevent="clickPage(pagebean.next)" :page-data="pagebean.next">下一页 {{pagebean.next}}</a>
			<a @click.prevent="clickPage(pagebean.totalpages)" :page-data="pagebean.totalpages">上一页
				{{pagebean.totalpages}}</a>
			总共条{{pagebean.total}}记录/共分{{pagebean.totalpages}}页
			每页{{pagebean.pagesize}}条,当前第{{pagebean.pageno}}页
			<br/>
			按<select name="sortby" v-model="pagebean.sortby">
			<option value="fid">菜品编号</option>
			<option value="realprice">成交价格</option>
		</select>
			<select name="sort" v-model="pagebean.sort">
				<option value="asc">升序</option>
				<option value="desc">降序</option>
			</select>
		</div>
	</div>
	  <!--  <div class="look">浏览记录</div> -->
<!--	  购物车模块-->
	  <div class="shoppingcar">
		  <div class="carbag" id="carbag" :class="{isShow:isHide==true,isHide:isHide==false}">
<!--			  <div class="carbag" id="carbag" class="isShow">-->
			  <p>购物车<span id="del" @click="clearAll()">[清空]</span></p>
			  <table id="bagcontent" cellpadding="0" cellspacing="0">
				  <tr v-for="cartfood in cartfoods">
					  <td class="bagfname">{{cartfood.food.fname}}</td>
					  <td class="bagnum">
						  <button @click="addCart(cartfood.food.fid,-1)">-</button>
						  {{cartfood.num}}
						  <button @click="addCart(cartfood.food.fid,1)">+</button>
					  </td>
				  </tr>
			  </table>
		  </div>
		  <div class="carprice" @click="showCart()">￥{{cartprice}}</div>
		  <div class="carinfo" v-if="cartfoods.length<=0">购物车是空的</div>
		  <div class="carinfo" v-else @click="orderflag=!orderflag">立即下单</div>
	  </div>
	<div class="footer">
		Copyright © 2016 Xiaomengsheng Incorporated Company. All rights reserved.
		<br />
		订餐，就上小萌神订餐网!
	</div>

	  <!--登录信息-->
	  <div class="login" id="login" v-if="loginflag">
		  <span id="unshow" @click="loginflag=false">X</span>
		  <form name="myform">
			  <table>
				  <tr>
					  <td class="labname"><label for="username">用户名：</label></td>
					  <td><input type="text" name="username" placeholder="请输入用户名"
								 id="username" v-model="username"/></td>
				  </tr>
				  <tr>
					  <td class="labname"><label for="pwd">密码：</label></td>
					  <td><input type="password" name="pwd" placeholder="请输入密码"
								 id="pwd" v-model="pwd"/></td>
				  </tr>
			  </table>
		  </form>
		  <input type="button" value="login" class="btn" id="btn" @click="login()"/>
	  </div>
	
	    <!-- 订单信息 -->
		<div class="login" id="myinfo" v-if="orderflag">
			<span id="unshowinfo" @click="changeShow()">X</span>
			<form name="forminfo">
				<table>
					<tr>
						<td class="labname"><label for="address">送货地址:</label></td>
						<td><input name="address"  type="text" placeholder="请输入送货地址" id="address" :val="orderInfo.address"/></td>
					</tr>
					<tr>
						<td class="labname"><label for="tel">联系电话:</label></td>
						<td><input type="text"  id="tel" placeholder="请输入联系电话" name="tel" :val="orderInfo.tel"/></td>
					</tr>
					<tr>
						<td class="labname"><label for="deliverytime">送货时间:</label></td>
						<td><input type="text"  name="deliverytime"
					   id="deliverytime" placeholder="请输入送货时间（默认马上发货）" :value="orderInfo.deliverytime"/>
							</td>
					</tr>
					<tr>
						<td class="labname"><label for="ps">附言:</label></td>
						<td><input type="text" id="ps" placeholder="请输入附言" name="ps" :value="orderInfo.ps"/></td>
					</tr>
				</table>
			</form>
			<input type="button" value="提交" class="btn" id="submit" @click="confirmOrder">
		</div>
		
</div>

	<!--  在网页里面引入javascript    jquery:DOM   大家注意顺序  -->
	<script src="js/jquery-1.9.1.js"></script>
	<script src="js/vue.js"></script>
	<script src="js/axios.js"></script>
	<script type="text/javascript">
		//使用axios时，利用原型模式给xios加 Authorization头，这样每个请求会加人Authorization头部
		Vue.prototype.axios = axios;
		// 每次请求时 前端携带token到请求头中
		axios.interceptors.request.use(config => {
			//从localStorage或vue中获取token
			const token = localStorage.getItem('token');
			//如果有token 就添加到请求头中
			// const seventhCharacterOnwards = token.substring(8);
			if (token) {
			// if (token&&seventhCharacterOnwards.startsWith('undefined')) {
				// 第七个字符开始的词以 "undefined" 开头
				config.headers.Authorization = token;
			}else{
				config.headers.token = '';
			}
			console.log("token: " + token);
			console.log("config " + config);
			return config;
		},error =>{
			return Promise.reject(error);
		});

		//配置访问的地址
		var base_url = "http://localhost:20001/";
		var addr_resfood = base_url + "resfood/";
		var addr_ressecurity = base_url + "ressecurity/";
		var addr_resorder = base_url + "order/";
		var addr_rescart = base_url + "cart/";
	     let vm=new Vue({
	    	 el:"#app",
	    	 data:{
	    		 orderflag:false,     //送货地址div
	    		 loginflag:false,      //登录窗口

				 isLogin:false,

				 //登录用的参数
				 username:'a',
				 pwd:'a',

				 data:[],  //显示菜品列表
				 cartfoods:[],  //购物车中的商品列表
				 cartprice:0.0,  //商品总价

				 //history:[],
				 isHide:false,
				 // historyflag:false,

				 //订单的model数据包装成一个对象
				 orderInfo:{
	    		 	address:'湖南',
					 tel:'12346',
					 deliverytime:'2023-08-31',
					 ps:'快'
				 },
				 //分页用的model
				 pagebean:{
	    		 	pageno:1,
					 pagesize:4,
					 sortby:'fid',
					 sort: 'asc',

					 total:0,
					 totalpages:0,
					 pre:1,
					 next:1
				 }
	    	 },
			 methods:{
				 changeShow: function () {
				 	this.orderflag=!this.orderflag;
				 },
	    	 	confirmOrder:function () {
					var params = new URLSearchParams(this.orderInfo);
					axios.post(addr_resorder+"orderFood",params).then(result=>{
						if (result.data.code == 1) {
							alert("下单成功");
							this.cartfoods = [];
							this.cartprice=0;
							this.isHide=false;
							this.orderflag=false;
						}
					});
				},
				 clearAll: function () {
					 axios.post(addr_rescart+"clearAll").then(result=>{
						 if (result.data.code == 1) {
							 alert("清除购物车成功");
							 this.cartfoods = [];
							 this.cartprice=0;
						 }
					 });
				 },
				 showCart:function () {
	    	 		this.isHide = !this.isHide;
				 },
				 addCart:function (fid,num) {
	    	 		//要添加购物车  需先保证登录通过
					 console.log("username:" + this.username);
					 if (this.username == null || this.username == '') {
					 	alert("请先登录");
					 	return;
					 }
					 //发出请求服务器
					 var params = new URLSearchParams();
					 params.append("num", num);
					 params.append("fid", fid);
					 axios.post(addr_rescart+"addCart",params).then(data=>{
					 	var jsonModel =data.data;
						 if (jsonModel.code == -1) {
							 alert("请先登录");
							 return;
						 }else if (jsonModel.code == 0) {
							 alert("添加购物车失败");
							 return;
						 }else {
						 	//todo：成功后显示购物车数据
							 this.showCartInfo(jsonModel.data);

						 }
					 });
				 },
				 showCartInfo:function (cart) {
	    	 		 this.cartfoods = cart;  //cartinfo是一个数组
					 //计算总价
					 this.cartprice=0.0;
					 this.cartfoods.forEach((item, idex) => {
					 	this.cartprice += item.smallCount;
					 });
				 },
				 showFood: function (fid) {
					 this.data.forEach((item, index) => {
					 	//当前循环的item的fid是否是我点的这个fid
						 item.status = fid == item.fid;
					 });
				 },
				 logout:function () {
					 // axios.post(addr_ressecurity + "logout").then(data => {
						 //todo:后端还没做
					 	// var result = data.data;
						 // if (result.code == 1) {
							 this.username = '';
							 this.pwd='';
							 this.isLogin=false;
							 this.history = [];
							 this.cartfoods = [];
							 this.cartprice = 0;

							 localStorage.removeItem("token");
						 // }
					 // });
				 },
				 login:function () {
					 var params = new URLSearchParams();
					 params.append("username", this.username);
					 params.append("pwd", this.pwd);
					 //post结果是一个Promise对象
					 axios.post(addr_ressecurity + "resfood/resuser.action", params).then(data => {
					 	var result = data.data;
					 	console.log("result: "+result)
						 if (result.jwttoken == '') {
							 alert("登陆失败，原因：" + result.msg);
							 return;
						 }
						 alert("登录成功!");
						 // this.username = result.data.username;
						 this.loginflag = false;
						 this.isLogin = true;

						 localStorage.setItem("token", "Bearer " + result.jwttoken);

					 });
				 },
				 checkLogin:function () {
					 if (this.username == null || this.username == '') {
						 return;
					 }
					 this.isLogin=true;
	    	 		//get的结果是一个Promise对象
					//  return axios.get(addr_ressecurity+"checkLogin.action")
					 //todo:后端还没做

				 },
				 findAllFoods:function () {
					 return axios.get(addr_resfood + "findAll");
				 },
				 showCartInit:function () {
					 var params = new URLSearchParams();
					 axios.post(addr_resorder + "getCartInfo", params).then(result => {
						 if (result.data.code == 1) {
							 this.showCartInfo(result.data.data);
						 }
					 });
				 },
				 clickPage:function (pageno) {
					 var promise = this.showPage(pageno);
					 promise.then(result => {
						 this.displayPage(result.data);
					 });
				 },
				 showPage:function(pageno) {
					 // var params = new URLSearchParams();
					 // params.append("pageno", pageno);
					 // params.append("sortby",this.pagebean.sortby);
					 // params.append("sort", this.pagebean.sort);
					 // params.append("pagesize", this.pagebean.pagesize);

					 return axios.get(addr_resfood + "findByPage?pageno="+pageno
							 + "&sortby="+this.pagebean.sortby
							 + "&sort="+this.pagebean.sort
							 + "&pagesize="+this.pagebean.pagesize);
					 // return axios.post(addr_resfood + "findByPage", params);
				 },
				 displayPage:function (result) {
					 let jsonModel2 = result;
					 if (jsonModel2.code == 1) {
					 	//显示数据到界面
						 //绑定到model中
						 jsonModel2.data.dataset.forEach((item, index) => {
						 	//给每个菜品对象添加一个熟悉，status用于控制这个菜品的详情 显示与隐藏
						 	item.status=false;
						 });

						 vm.$data.data=jsonModel2.data.dataset; // 菜品列表数据
						 vm.$data.pagebean=jsonModel2.data;

					 }

				 }
			 },
			 computed:{

			 },
			 mounted:function () {
				axios.all([this.showPage(1),this.checkLogin()]).then(axios.spread(function (d2,d3) {
					let json = d2.data;
					if(json.code == 1){
						vm.displayPage(json);
					}

				}))
			 }

	     });
	     const data = vm.$data;

	</script>
	
</body>
</html>